package edu.msu.scrabble.project1;

import com.google.android.gcm.GCMRegistrar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LogInActivity extends Activity {
	
	private final static String USERNAME = "username";
	private final static String PASSWORD = "password";
	private final static String REMEMBER = "remember";

	// for storing username and password on the device
	public static final String PREFERENCES = "preferences";
	
	private Cloud thecloud = null;
	
	private String username = null;
	
	private String password = null;
	
	private Boolean remember = null;
	
	private EditText usernameEditText = null;
	
	private EditText passwordEditText = null;

	private CheckBox rememberCheckbox = null;
	
	private SharedPreferences preferences = null;
	
	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_log_in);
		
		thecloud = Cloud.get();
		
		// Set up GCM
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		String regId = GCMRegistrar.getRegistrationId(this);
		if(regId.equals("")) {
			GCMRegistrar.register(this,GCMIntentService.SENDER_ID);
		} else {
			// Send the id to the cloud
			thecloud.setGcmId(regId);
		}
		
		// get the edittexts used for entering username and password
		usernameEditText = (EditText)findViewById(R.id.usernameText);
		passwordEditText = (EditText)findViewById(R.id.passwordText);
		rememberCheckbox = (CheckBox)findViewById(R.id.rememberCheckBox);
		
		preferences = getSharedPreferences(PREFERENCES,0);
		remember = preferences.getBoolean(REMEMBER,false);
		if(remember){
			username = preferences.getString(USERNAME, null);
			password = preferences.getString(PASSWORD, null);
			
			usernameEditText.setText(username);
	        passwordEditText.setText(password);
		}
		
		// fill out information if there is a saved state
		if(savedInstanceState != null) {
            username = savedInstanceState.getString(USERNAME);
            password = savedInstanceState.getString(PASSWORD);
            remember = savedInstanceState.getBoolean(REMEMBER);
            
            
            usernameEditText.setText(username);
            passwordEditText.setText(password);
            
        }
		rememberCheckbox.setChecked(remember);
		// check for data coming from the createuser activity
		if((savedInstanceState = getIntent().getExtras()) != null) {
			username = savedInstanceState.getString(USERNAME);
            password = savedInstanceState.getString(PASSWORD);
			
            usernameEditText.setText(username);
            passwordEditText.setText(""); //-- the point of sending to the user to log in after create is to verify the password
		}
	}
	
	/*
	 * If the user is logged in pass them onto waiting
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		if(thecloud.loggedIn()) {
			Intent intent = new Intent(this, PlaceHolderActivity.class);
			startActivity(intent);
			finish();
		}
	}
	
	
	/**
	 * Attempt to log user in
	 */
	public void onLogIn(View view) {
		username = usernameEditText.getText().toString();
        password = passwordEditText.getText().toString();
        remember = rememberCheckbox.isChecked();
		
		final ContextWrapper activity = this;
		final Handler mainHandler = new Handler(this.getMainLooper());
		
		/*
         * Create a thread to attempt to log in the user from the cloud
         */
        new Thread(new Runnable() {
        	
            @Override
            public void run() {
            	final boolean loggedin = thecloud.logInToCloud(username, password);
            	
            	mainHandler.post(new Runnable() {
            		/*
            		 * If the user was logged in then we can send them to the next activity
            		 */
            		@Override
    	            public void run() {
            			if (loggedin){
            				SharedPreferences.Editor editor = preferences.edit();
            				editor.putBoolean(REMEMBER,remember);
            				if (remember)
            				{
            					// save the username and password into preferences
            					editor.putString(USERNAME, username);
            					editor.putString(PASSWORD, password);
            				}
            				editor.commit();
            				thecloud.setUsername(username);
            				
            				Intent intent = new Intent(activity, PlaceHolderActivity.class);
            				startActivity(intent);
            				finish();
    	            	}
    	                else
    	                {
    	                	// output a message saying login was unsuccessful
    	                	Toast.makeText(activity, R.string.login_failed, Toast.LENGTH_SHORT).show();
    	                }
                    }
            	});
            }
        }).start();
	}
	
	
	/**
	 * Open the activity to create a new user
	 */
	public void onCreateUser(View view) {
		Intent intent = new Intent(this, CreateUserActivity.class);
		startActivity(intent);
	}
	
	
	/**
	 * This is just a test to make sure I am keeping track of the session properly
	 * The user will be bounced back to log-in if this button is hit before logging in
	 * This can be taken out after initial testing -Mike
	 */
	public void onTest(View view) {
		Intent intent = new Intent(this, PlaceHolderActivity.class);
		startActivity(intent);
	}
	
	
	/** 
     * Save the instance state
     */
    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        
        username = usernameEditText.getText().toString();
        password = passwordEditText.getText().toString();
        remember = rememberCheckbox.isChecked();
        
        bundle.putString(USERNAME, username);
        bundle.putString(PASSWORD, password);
        bundle.putBoolean(REMEMBER, remember);
    }

}
